package org.light4admin.common.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.light4admin.modules.system.utils.SecurityUtils;
import org.light4admin.util.IdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.Properties;


/**
 * <p>
 * 自动字段操作拦截器
 * </p>
 *
 * @author light4admin
 * @date 2018/8/3
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class AuditFieldsOperationInterceptor implements Interceptor {

    private static final String CREATEBY = "createBy";//创建人

    private static final String UPDATEBY = "updateBy";//更新人


    private static final String ID = "id";
    private static final String ENTITY = "et";


    @Autowired
    private IdGeneratorUtil idGeneratorUtil;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        if (SqlCommandType.SELECT == sqlCommandType) {
            return invocation.proceed();
        }

        Object object = args[1];
        if (Objects.isNull(object)) return object;

        if (object instanceof HashMap) {
            HashMap<String, Object> params = (HashMap<String, Object>) object;
            if (params.containsKey(ENTITY)) {
                setAuditFields(params.get(ENTITY), sqlCommandType);
            }
        } else {
            setAuditFields(object, sqlCommandType);
        }
        return invocation.proceed();
    }

    /**
     * 设置审计字段
     *
     * @param object 参数
     * @param type   sql类型
     * @throws IllegalAccessException
     */
    private void setAuditFields(Object object, SqlCommandType type) throws IllegalAccessException {
        Field[] fields = object.getClass().getDeclaredFields();

        //操作人
        Long userId = SecurityUtils.getUserId();


        for (Field field : fields) {
            field.setAccessible(true);
            switch (type) {
                case UNKNOWN:
                    break;
                case INSERT:
                    if (Objects.isNull(field.get(object))) {
                        // 只有insert时，才根据是否传create_time等而设值
                        if (Objects.equals(field.getName(), ID)) {
//                            field.set(object, idGeneratorUtil.getId());//用数据库自增，暂不用雪花算法
                            continue;
                        }


                        //创建人、创建人Id
                        if (Objects.equals(field.getName(), CREATEBY)) {
                            field.set(object, userId + "");
                        }
                    }
                    break;
                case UPDATE:
                case DELETE:
                    //更新人、更新人Id
                    if (Objects.equals(field.getName(), UPDATEBY)) {
                        field.set(object, userId + "");
                    }
                    break;
                case SELECT:
                    break;
                case FLUSH:
                    break;
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
